/*
* " - qo'shtirnoq proyekt turgan joydan qidiradi
* <> - compiler papkasidan qidiradi
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "include\CIp.h"
#include <math.h>
CIp::CIp()
{
    //ctor
}

CIp::~CIp()
{
    //dtor
}
/**
* Kiritilgan matnni CIDR ko'rinishida yozilganligini tekshiradi
*/
bool CIp::IsCidr(char *cidr)
{
    int l = strlen(cidr);
    if (l < 7 || l > 18) return false;

    short p[5];
    char i = 0;
    for(i = 0; i < 5; i++) p[i] = -1;

    sscanf(cidr, "%d.%d.%d.%d/%d", &p[0], &p[1], &p[2], &p[3], &p[4]);

    for(i = 0; i < 4; i++)
        if (p[i] < 0 || p[i] > 255) return false;

    if (p[4] < 0 || p[4] > 32) return false;
    return true;
}
/**
* Kiritilgan matnni IP/MASK ko'rinishida yozilganligini tekshiradi
*/
bool CIp::IsIpMask(char *ipmask)
{
	int a[4], b[4];
	for(int i = 0; i < 4; i++ ){
		a[i] = -1;
		b[i] = -1;
	}
	sscanf(ipmask, "%d.%d.%d.%d/%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3], &b[0], &b[1], &b[2], &b[3]);
	for(int i = 0; i < 3; i++){
		if(a[i]>b[i]){
			return false;
		}
	}
	if(b[3] != 0)
		return false;
	return true;
}

/**
* Kiritilgan matnni IP turiga mos kelishini tekshiradi
*/
bool CIp::IsIp(char *ip)
{
    int l = strlen(ip);
    if (l < 7 || l > 15) return false;

    short p[4];  char i = 0;

    for(i = 0; i < 4; i++)
        p[i] = -1;

    sscanf(ip, "%d.%d.%d.%d", &p[0], &p[1], &p[2], &p[3]);

    for(i = 0; i < 4; i++)
        if (p[i] < 0 || p[i] > 255) return false;

    return true;
}

/**
* IP in IP/MASK (CIDR)
*/
bool CIp::IpInCidr(char *ip, char *cidr)
{
    if (!this->IsIp(ip)) return false;
    if (!this->IsCidr(cidr)) return false;
    char *p;
    p = strtok(cidr, "/");
    unsigned int ip1 = Ip2Int(ip), min = Ip2Int(p);
    p = strtok(NULL, "/");
    int k = atoi(p);
    unsigned int max = 0xFFFFFFFF;
    max <<= (32-k);
    min >>= (32-k);
    min <<= (32-k);
    max = ~max;
    return (ip1 >= min) && (ip1 <= (max | min));
}

unsigned int CIp::Ip2Int(char *ip)
{
    unsigned int p1, p2, p3, p4;
    sscanf(ip, "%d.%d.%d.%d", &p1, &p2, &p3, &p4);
    p1 <<= 24; p2 <<= 16; p3 <<= 8;
    return p1 | p2 | p3 | p4;
}

/*char * CIp::Int2Ip(unsigned int ipInt)
{
    unsigned char   p1 = (ipInt >> 24) & 0xFF,
                    p2 = (ipInt >> 16) & 0xFF,
                    p3 = (ipInt >> 8) & 0xFF,
                    p4 = ipInt & 0xFF;
    //printf("%d.%d.%d.%d\n", p1, p2, p3, p4);
}*/
